using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GraphicsTests
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        GraphicsDevice device;
        RenderTarget2D renderTarget;
        SpriteBatch spriteBatch;
        Effect effect;
        Effect postProcess;
        Vector3 lightDirection = new Vector3(0, 5, -3);
        Matrix viewMatrix;
        Matrix projectionMatrix;
        Model monkey;
        Vector3 CameraPosition = new Vector3(2, 2, 5);
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            graphics.PreferredBackBufferWidth = 500;
            graphics.PreferredBackBufferHeight = 500;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Window.Title = "effects testing ground";
            spriteBatch = new SpriteBatch(GraphicsDevice);
            renderTarget = new RenderTarget2D(GraphicsDevice, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight, 1, GraphicsDevice.PresentationParameters.BackBufferFormat);

            lightDirection.Normalize();
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            device = graphics.GraphicsDevice;


            effect = Content.Load<Effect>("effects");
            postProcess = Content.Load<Effect>("PostProcessing");
            monkey = LoadModel("monkey");
            viewMatrix = Matrix.CreateLookAt(CameraPosition, new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.2f, 500.0f);
            // TODO: use this.Content to load your game content here
        }
        private Model LoadModel(string assetName)
        {

            Model newModel = Content.Load<Model>(assetName); foreach (ModelMesh mesh in newModel.Meshes)
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                    meshPart.Effect = effect.Clone(device);
            return newModel;
        }
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            Texture2D texture = DrawSceneToTexture(renderTarget);

            GraphicsDevice.Clear(Color.Black);
            
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            postProcess.Begin();
            for (int index = 0; index < postProcess.CurrentTechnique.Passes.Count; index++)
            {
                postProcess.CurrentTechnique.Passes[index].Begin();

                spriteBatch.Draw(texture, new Rectangle(0, 0, GraphicsDevice.PresentationParameters.BackBufferWidth, GraphicsDevice.PresentationParameters.BackBufferHeight), Color.White);
                postProcess.CurrentTechnique.Passes[index].End();
            }

            postProcess.End();

            spriteBatch.End();
            base.Draw(gameTime);
        }
        protected Texture2D DrawSceneToTexture(RenderTarget2D renderTarget)
        {
            // Set the render target
            GraphicsDevice.SetRenderTarget(0, renderTarget);

            device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);


            // TODO: Add your drawing code here
            Matrix worldMatrix = Matrix.Identity;

            Matrix[] monkeyTransform = new Matrix[monkey.Bones.Count];
            monkey.CopyAbsoluteBoneTransformsTo(monkeyTransform);
            foreach (ModelMesh mesh in monkey.Meshes)
            {
                foreach (Effect currentEffect in mesh.Effects)
                {
                    currentEffect.CurrentTechnique = currentEffect.Techniques["Colored"];
                    currentEffect.Parameters["xWorld"].SetValue(monkeyTransform[mesh.ParentBone.Index] * worldMatrix);
                    currentEffect.Parameters["xView"].SetValue(viewMatrix);
                    currentEffect.Parameters["xProjection"].SetValue(projectionMatrix);
                    currentEffect.Parameters["xEnableLighting"].SetValue(true);
                    currentEffect.Parameters["xLightDirection"].SetValue(lightDirection);
                    currentEffect.Parameters["xAmbient"].SetValue(0.1f);
                    currentEffect.Parameters["xDiffuseK"].SetValue(1.0f);
                    currentEffect.Parameters["xSpecularK"].SetValue(0.8f);
                    currentEffect.Parameters["xShine"].SetValue(50.0f);
                    currentEffect.Parameters["xCameraPosition"].SetValue(CameraPosition);
                    currentEffect.Parameters["xLightArray"].StructureMembers["Position"].SetValue(new Vector3(0, 5, 0));
                    currentEffect.Parameters["xLightArray"].StructureMembers["Color"].SetValue(new Vector4(1.0f, 1.0f, 0.8f, 1.0f));

                }
                mesh.Draw();
            }
            // Drop the render target
            GraphicsDevice.SetRenderTarget(0, null);

            // Return the texture in the render target
            return renderTarget.GetTexture();
        }
    }
}
